package com.eolcum.evo.thread;

import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import com.eolcum.evo.persistence.DataBaseHelper;
import com.eolcum.evo.persistence.Room;
import com.eolcum.evo.persistence.ScheduleSetpoint;

public class TimeProgramController implements Runnable {

	private Room room;
	private int cycleFrequency = 1000;

	private DataBaseHelper dbHelper;
	
	public TimeProgramController() {}

	@Override
	public void run() {
		room.setActualTemperatureSetpoint(dbHelper.getInstantSetpoint(room.getId()));
		List<ScheduleSetpoint> dailySchedule = dbHelper.getDailySchedule(room.getId());
		Collections.sort(dailySchedule);
		room.setDailyTimeSchedule(dailySchedule);
		int count = 0;
		while (true) {
			if (dbHelper.getUpdatedTimePrograms().size() > 0) {
				for (int i = 0; i < dbHelper.getUpdatedTimePrograms().size(); i++) {
					if (dbHelper.getUpdatedTimePrograms().get(i) == room.getId()) {
						dailySchedule = dbHelper.getDailySchedule(room.getId());
						Collections.sort(dailySchedule);
						room.setDailyTimeSchedule(dailySchedule);
						count = 0;
						break;
					}
				}
			} else if (count > 82800000 / cycleFrequency) {
				dailySchedule = dbHelper.getDailySchedule(room.getId());
				Collections.sort(dailySchedule);
				room.setDailyTimeSchedule(dailySchedule);
				count = 0;
			}
			count++;
			if(room.getDailyTimeSchedule().size() > 0 && Calendar.getInstance().getTimeInMillis() > room.getDailyTimeSchedule().get(0).getTime().getTime()) {
				room.setActualTemperatureSetpoint(Double.valueOf(room.getDailyTimeSchedule().get(0).getTempSetpoint()));
				room.getDailyTimeSchedule().remove(0);
			}
			try {
				Thread.sleep(cycleFrequency);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @return the room
	 */
	public synchronized Room getRoom() {
		return room;
	}

	/**
	 * @param room the room to set
	 */
	public synchronized void setRoom(Room room) {
		this.room = room;
	}
	public DataBaseHelper getDbHelper() {
		return dbHelper;
	}

	public void setDbHelper(DataBaseHelper dbHelper) {
		this.dbHelper = dbHelper;
	}
}
